package com.tangyuan.live.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import com.tangyuan.live.entity.dto.ManagementDto;
import com.tangyuan.live.entity.enums.LiveManagementTypeEnum;
import com.tangyuan.live.mapper.LiveManagementMapper;
import com.tangyuan.live.service.LiveManagementService;
import com.tangyuan.live.service.LiveRoomService;
import com.tangyuan.live.service.LiveViewRecordService;
import com.tangyuan.live.util.IMUtil;
import com.tangyuan.model.live.LiveManagement;
import com.tangyuan.model.live.LiveRoom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LiveManagementServiceImpl extends ServiceImpl<LiveManagementMapper, LiveManagement>
         implements LiveManagementService{

    @Autowired
    LiveRoomService liveRoomService;
    @Autowired
    LiveViewRecordService liveViewRecordService;
    @Autowired
    IMUtil imUtil;


    @Override
    public Result<ResultCodeEnum> shiftOutUser(Long userId, ManagementDto dto) {
        Result<LiveRoom> result = liveRoomService.getLiveRoomById(dto.getRoomId());
        if(!result.isOk()){
            return Result.build(null,result.getCode(),result.getMessage());
        }
        LiveRoom liveRoom = result.getData();
        List<LiveManagement> liveManagements = new ArrayList<>();
        for (Long id : dto.getUserIds()) {
            LiveManagement liveManagement = LiveManagement.builder()
                    .shutUpCause(dto.getShutUpCause())
                    .roomId(liveRoom.getId())
                    .operateUserId(userId)
                    .userId(id)
                    .type(LiveManagementTypeEnum.SHIFT_OUT.type)
                    .build();
            liveManagements.add(liveManagement);
        }
        this.saveBatch(liveManagements);
        List<String> list = dto.getUserIds().stream().map(String::valueOf).collect(Collectors.toList());
        imUtil.shiftOutUser(liveRoom.getGroupId(),list);
        return Result.ok();
    }

    /**
     * 检查用户在房间中的发言状态
     * @param userId 用户ID，用于标识需要检查的用户
     * @param roomId 房间ID，用于标识用户所在的房间
     * @param type 判断类型，用于指定需要检查的状态类型（例如，1: 是否禁言；2: 是否限时发言）
     * @return 返回布尔值，true表示用户处于指定的状态（如禁言或限时发言），false则否
     */
    @Override
    public boolean isShiftOutOrShutUp(Long userId, Long roomId, Integer type) {
        QueryWrapper<LiveManagement> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(LiveManagement::getRoomId,roomId);
        wrapper.lambda().eq(LiveManagement::getOperateUserId,userId);
        wrapper.lambda().eq(LiveManagement::getType,type);
        wrapper.lambda().eq(LiveManagement::getIsDelete,0);
        return baseMapper.selectOne(wrapper) != null;
    }

    @Override
    public Result<ResultCodeEnum> shutUpUser(Long userId, ManagementDto dto) {
        Result<LiveRoom> result = liveRoomService.getLiveRoomById(dto.getRoomId());
        if(!result.isOk()){
            return Result.build(null,result.getCode(),result.getMessage());
        }
        LiveRoom liveRoom = result.getData();
        LambdaQueryWrapper<LiveManagement> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LiveManagement::getRoomId,liveRoom.getId());
        wrapper.in(LiveManagement::getUserId,dto.getUserIds());
        List<LiveManagement> managements = baseMapper.selectList(wrapper);
        List<Long> ids = dto.getUserIds();
        List<String> shiftOutList = new ArrayList<>();
        List<String> cancelShiftOutList = new ArrayList<>();

        for (LiveManagement management : managements) {
            ids.remove(management.getUserId());
            if(management.getIsDelete() == 0){
                management.setIsDelete(1);
                cancelShiftOutList.add(management.getUserId().toString());
            }else{
                shiftOutList.add(management.getUserId().toString());
                management.setIsDelete(0);
            }
        }
        for (Long id : dto.getUserIds()) {
            LiveManagement liveManagement = LiveManagement.builder()
                    .shutUpCause(dto.getShutUpCause())
                    .roomId(liveRoom.getId())
                    .operateUserId(userId)
                    .userId(id)
                    .type(LiveManagementTypeEnum.SHUT_UP.type)
                    .build();
            managements.add(liveManagement);
            shiftOutList.add(id.toString());
        }
        //禁言
        imUtil.shutUpUser(liveRoom.getGroupId(), shiftOutList, 60 * 60 * 24);
        //取消禁言
        imUtil.shutUpUser(liveRoom.getGroupId(), cancelShiftOutList, 0);
        this.saveOrUpdateBatch(managements);

        return Result.ok();
    }


}
